//$(function (){
//    loadStudentList();
//});
//function loadStudentList(){
//    $.ajax({
//        url:"/api/student/list"
//    }).done(function (data){
//        //console.log(data)
//        let html="";
//        data.forEach((element,index) => {
//            html+="<tr>"
//            html+="<td>"+element.id+"</td>"
//            html+="<td>"+element.name+"</td>"
//            html+="<td>"+element.sex+"</td>"
//            html+="<td>"+element.age+"</td>"
//            html+="<td>"+element.sno+"</td>"
//            html+="<td> <a href='#' onclick='showStudentDlg("+element.id
//                +")'>编辑</a> &nbsp;&nbsp;<a href='#' onclick='deleteById("+
//                +element.id+")'>删除</a></td>"
//            html+="</tr>"
//        })
//        $("#studentTb").html(html)
//    });
//}
let layerIndex;
/**
 * 弹出老师新增对话框
 */
function showStudentDlg(id){
    let title="新增老师"
    $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
    if (id){
        title="编辑老师"
        $("#formId").css("display","block");
        $.ajax({
            url:"/api/student/"+id,
            method: "GET"
        }).done(result=>{
            console.log(result)
            $.each(result,function (key,value) {
                var field = $('#studentForm [name="'+key+'"]');
                if(field.is(':radio')){
                    field.filter('[value="'+value+'"]').prop('checked',true);
                }else if(field.is(':checkbox')){
                    field.prop('checked',value==="yes");
                }else{
                    field.val(value);
                }
            });
        })
    }else{
        $("#studentForm")[0].reset();
        $("#formId").css("display","none");
    }
    layerIndex = layer.open({
        type: 1,
        title: "新增老师",
        area: ['520px','auto'],
        content: $('#studentForm')
    });
}
function getSearchCondition(){
    let formData={}
    $('#queryForm').find('input,select').each(function(){
        let name=$(this).attr("name");
        let value=$(this).val();
        if(name&&value){
            formData[name]=value;
        }
    });
    return formData;
}
layui.use(function (){
    layui.form.on('submit(student-dlg)', function(data) {
        event.preventDefault();
        commitStudentDlg();
    })
    const table=layui.table;
    let student=getSearchCondition();
    table.render({
        elem:'#tbStudent',
        url:'/api/student/getbypage',
        //此处为静态模拟数据，实际使用时需换成真实接口
        method:"POST",
        contentType:'application/json',
        where:{"data":student},
        page:true,
        cols:[[
            {type: 'checkbox',fixed:'left'},
            {field: 'id',fixed: 'left',width:80,title:'id',sort:true},
            {field: 'name',title: '姓名'},
            {field: 'sno',title: '工号',width: 150},
            {field: 'sex',width: 80,title: '性别',sort: true,templet:d=>d.sex===1?'男' :(d.sex===2?'女':'未知')},
            {field: 'age',width: 100,title: '年龄',sort: true},
            {field: 'right',title: '操作',width: 134,minwidth:125,templet:'#editTemplate'}
        ]],
        done:function (rs){
            //console.log(rs)
        }
});
    //触发单元格工具事件
    table.on('tool(tbStudent)',function (obj){
        var data =obj.data;
        if(obj.event==='edit'){
            $("#btnOk").prop("disabled",false).removeClass("layui-btn-disabled");

            //数据填充表单
            $.each(data,function(key,value){
                //修改选择器，确保选择的是#teachForm内的字段
                var field=$('#studentForm [name="' + key + '"]');
                if(field.is(':radio')){
                    field.filter('[value="'+value+'"]').prop('checked',true);
                    //选中对应的单选按钮
                }
                else if(field.is(':checkbox')){
                    field.prop('checked',value ==="yes");//选中复选框
                }
                else{
                    field.val(value);//填充文本框或其他字段
                }
            });

            layerIndex=layer.open({
                title:'编辑 - id:'+data.id,
                type:1,
                area:['80%','80%'],
                content:$("#studentForm")
            });
        }
    })
});
function search(){
    let student=getSearchCondition();
    const table=layui.table;
    table.reloadData("tbStudent",{
        where: {data:student}
    });
    console.log("where condition:"+JSON.stringify(student))
}
function deleteConfirm(){
    const table=layui.table;
    //获取表格的选中状态
    const checkStatus=table.checkStatus('tbStudent');
    console.log(checkStatus.data);
    const ids=checkStatus.data.map(item=>item.id);
    if(ids.length===0){
        layer.msg('请选择要删除的教师!',{icon:2});
        return;
    }
    layer.confirm('是否删除？一旦删除，不可恢复',{icon:3},function () {
        $.ajax({
            url:"/api/student/deleteId/"+ids.join(","),
            method:"DELETE",
        }).done(result=>{
            search();
        })
        layer.closeAll();//关闭所有层
    },function (){
    });
}
function commitStudentDlg(){
    let id= $("#id").val()
    let formData = $("#studentForm").serialize();
    if(id!=null && id!=""){
        $.ajax({
            url:"/api/student/update",
            method:"PUT",
            data:formData
        }).done(result=>{
            console.log(result);
            if(result.id){
                loadStudentList();
                console.log("update success")
                if (layerIndex)
                    layer.close(layerIndex);
            }
        }).fail((jqXHR, textStatus, errorThrown)=>{
            console.error("Request failed:"+ textStatus + "-" + errorThrown);
            alert("An error occurred. Please try again later.");
        });
    }else{
        $.ajax({
            url:"/api/student/add",
            method:"POST",
            data:formData
        }).done(result=>{
            console.log(result);
            if(result.id){
                loadStudentList();
                console.log("add success")
                if (layerIndex)
                    layer.close(layerIndex);
            }
        }).fail((jqXHR, textStatus, errorThrown)=>{
            console.error("Request failed:"+ textStatus + "-" + errorThrown);
            alert("An error occurred. Please try again later.");
        });
    }

    $("#btnOK").prop("disabled",true).addClass("layui-btn-disabled");
}

//function deleteById(id){
//    //删除
//    layer.confirm('你确认要删除吗？一旦删除，不可恢复',{icon: 3},function(){
//        $.ajax({
//            url:"/api/student/delete/"+id,
//            method:"DELETE"
//        }).done(result=>{
//            loadStudentList();
//        })
//        layer.closeAll();
//    }, function(){
//
//    });
//}